package postgres

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	logger "pay/collector/logger"
	"pay/config"
	"pay/errors"
	"pay/model"
	"pay/model/entity"
	"pay/utils"
)

var FeePlan = &feePlan{}

type feePlan struct{}

func init() {
	Register(FeePlan)
}

func (a *feePlan) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.FeePlan{}
		if db.Migrator().HasTable(p) {
			logger.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := db.AutoMigrate(p); err != nil {
			logger.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			logger.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *feePlan) Create(ctx context.Context, m *entity.FeePlan) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *feePlan) Find(ctx context.Context, in *model.FeePlanInfoRequest) (*entity.FeePlan, error) {
	e := &entity.FeePlan{}

	q := GetDB(ctx).Model(&entity.FeePlan{})

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}
	err := q.First(&e, in.Id).Error
	return e, err
}

// Update
func (a *feePlan) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.FeePlan{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *feePlan) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.FeePlan{}, id).Error
}

// List query list
func (a *feePlan) List(ctx context.Context, in *model.FeePlanListRequest, opts ...model.QueryOptions) (int, []*entity.FeePlan, error) {

	var (
		opt      = model.GetQueryOption(opts...)
		q        = GetDB(ctx).Model(&entity.FeePlan{})
		err      error
		total    int64
		feePlans []*entity.FeePlan
	)

	if in.Id != nil {

		q = q.Where("id = ?", in.Id)

	}

	if len(in.Ids) > 0 {
		q = q.Where("id IN ?", in.Ids)
	}

	if in.Name != nil {

		q = q.Where("name like ?", utils.SqlLike(in.Name))

	}

	if in.Type != nil {

		q = q.Where("type = ?", in.Type)

	}

	if in.Enable != nil {

		q = q.Where("enable = ?", in.Enable)

	}

	if in.Packs != nil {

		q = q.Where("packs = ?", in.Packs)

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if len(opt.SelectFields) > 0 {
		q = q.Select(opt.SelectFields)
	}

	if len(opt.OrderFields) > 0 {
		q = q.Order(fmt.Sprintf("%v", model.ParseOrder(opt.OrderFields)))
	}

	b := !opt.OnlyCount && !opt.OnlyList
	if opt.OnlyCount || b {
		if err = q.Count(&total).Error; err != nil {
			return 0, nil, err
		}
	}

	if opt.OnlyList || b {
		if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&feePlans).Error; err != nil {
			return 0, nil, err
		}
	}

	return int(total), feePlans, nil
}

// ExecTransaction execute database transaction
func (a *feePlan) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
